package activity;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.example.administrator.ci_edit.R;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import db.UserConfigDatabaseHelper;
import model.Constants;
import util.FileUtils;

/**
 * Created by Administrator on 2017/7/16.
 */

public class DaShangActivity extends AppCompatActivity {

    private View imgview_dashang;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashang);

        imgview_dashang = (ImageView) findViewById(R.id.imgview_dashang);

//        imgview_dashang.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//
//                //在这里输入要跳转的界面
////                Toast.makeText(getApplicationContext(), "这个app不适合你",
////                        Toast.LENGTH_SHORT).show();
////               System.exit(0);
//            }
//        });

        //长按，通过zxing读取图片，判断是否有二维码
        imgview_dashang.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View viewm) {
                //Bitmap obmp = ((BitmapDrawable) (imgview_dashang).getDrawable()).getBitmap();
                Bitmap obmp = drawableToBitmap(ContextCompat.getDrawable(getApplicationContext(), R.mipmap.dashang));
                //Bitmap obmp = (BitmapDrawable)(imgview_dashang).getBitmap();
                int width = obmp.getWidth();
                int height = obmp.getHeight();
                int[] data = new int[width * height];
                obmp.getPixels(data, 0, width, 0, 0, width, height);
                RGBLuminanceSource source = new RGBLuminanceSource(width, height, data);
                BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
                QRCodeReader reader = new QRCodeReader();
                Result re = null;

                try {
                    re = reader.decode(bitmap1);
                } catch (NotFoundException e) {
                    e.printStackTrace();
                } catch (ChecksumException e) {
                    e.printStackTrace();
                } catch (com.google.zxing.FormatException e) {
                    e.printStackTrace();
                }

                if (re == null) {
                    showAlert(obmp);
                } else {
                    showSelectAlert(obmp, re.getText());
                }
                return false;
            }
        });
    }






    public static Bitmap drawableToBitmap(Drawable drawable) {


        Bitmap bitmap = Bitmap.createBitmap(

                drawable.getIntrinsicWidth(),

                drawable.getIntrinsicHeight(),

                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888

                        : Bitmap.Config.RGB_565);

        Canvas canvas = new Canvas(bitmap);

        //canvas.setBitmap(bitmap);

        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());

        drawable.draw(canvas);

        return bitmap;

    }

    private void showAlert(final Bitmap bitmap) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("保存图片")
                .setCancelable(false)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterfacem, int i) {
                        //saveImageToGallery(bitmap);
                        try{
                        FileUtils.saveFile(bitmap, "test");// TODO: 2017/7/16
                        }catch (IOException e){//lily sb
                             }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterfacem, int i) {
                    }
                });
        builder.show();
    }

    private void showSelectAlert(final Bitmap bitmap, final String url) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请选择");
        String str[] = {"保存图片", "扫二维码"};
        builder.setItems(str, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterfacem, int i) {
                switch (i) {
                    case 0: {
                        try {
                            //saveImageToGallery(bitmap, Constants.File_PATH);//// TODO: 2017/7/16
                            FileUtils.saveFile(bitmap,"日行一善");

                        }catch (IOException e){}
                    }
                    break;
                    case 1: {
                        //// TODO: 2017/7/16
                        UserConfigDatabaseHelper.changeToVip();

//                            Intent n = new Intent(DaShangActivity.this, DetailActivity.class);
//                            n.putExtra(DetailActivity.BUNDLE_KEY_DISPLAY_TYPE, DetailActivity.WEBVIEW_DETAIL);
//                            n.putExtra(DetailwebFragment.WEB_URL, url);
//                            startActivity(n);

                        //String http = QRCodeUtils.getStringFromQRCode(drawable);
                        //String http =
                    }
                    break;
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterfacem, int i) {

            }
        });
        builder.show();
    }


//    public static void saveImageToGallery(Context context, Bitmap bmp) {
//        // 首先保存图片
//        File appDir = new File(Environment.getExternalStorageDirectory(), "ci_helper");
//        if (!appDir.exists()) {
//            appDir.mkdir();
//        }
//        String fileName = System.currentTimeMillis() + ".jpg";
//        File file = new File(appDir, fileName);
//        try {
//            FileOutputStream fos = new FileOutputStream(file);
//            bmp.compress(Bitmap.CompressFormat.JPEG .JPEG, 100, fos);
//            fos.flush();
//            fos.close();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        // 其次把文件插入到系统图库
//        try {
//            MediaStore.Images.Media.insertImage(context.getContentResolver(),
//                    file.getAbsolutePath(), fileName, null);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//        // 最后通知图库更新
//        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
//    }
public static void saveImageToGallery(Bitmap bitmap, String _file)
        throws IOException {
    BufferedOutputStream os = null;
    try {
        File file = new File(_file);
        // String _filePath_file.replace(File.separatorChar +
        // file.getName(), "");
        int end = _file.lastIndexOf(File.separator);
        String _filePath = _file.substring(0, end);
        File filePath = new File(_filePath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        file.createNewFile();
        os = new BufferedOutputStream(new FileOutputStream(file));
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
    }
//    catch (IOException e){
//        // lily sb
//    }
    finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                Log.e("TAG_ERROR", e.getMessage(), e);
            }
        }
    }
}
}

